<?php
namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\OrderInfo;
use app\models\OrderInfoGood;
use app\models\OrderOffline;
use app\tools\Re;
use Yii;

class OrderController extends BaseController
{
    public $state_arr = ['待付款', '待发货', '待收货', '已完成', '已取消', '租赁中', '已评价'];

    //订单列表
  	public function actionOrderList() {
  		$page = Yii::$app->request->post('page', 0);
      $phone = Yii::$app->request->post('phone', '');
      $order_sn = Yii::$app->request->post('order_sn', '');
      $state = Yii::$app->request->post('state', -2);
      $date_range = Yii::$app->request->post('created_at_range', '');

      $order_query = OrderInfo::find()
        ->leftJoin('user', 'order_info.user_id = user.id')
        ->where(['order_info.status' => 1]);
      if ($phone) {
        $order_query->andWhere(['like', 'phone', $phone]);
      }
      if ($date_range) {
        $data_arr = explode("-", $date_range);
        $start_at = $data_arr[0];
        $end_at = $data_arr[1];
        $order_query->andWhere("order_info.created_at >= '$start_at' and order_info.created_at <= '$end_at'");
      }
      if ($order_sn) {
        $order_query->andWhere(['like', 'order_sn', $order_sn]);
      }
      if ($state > -1) {
        $order_query->andWhere(['state' => $state]);
      }
  		$list = $order_query->orderBy("created_at desc")->limit(OrderInfo::PAGE_SIZE)->offset(OrderInfo::PAGE_SIZE*$page)->all();
        $order_data = [];
        if ($list) {
            foreach ($list as $v) {
                $order_good = OrderInfoGood::find()->where(['order_id' => $v->id])->one();
                $order_data[] = [
                  'id' => $v->id,
                  'order_sn' => $v->order_sn,
                  'money' => bcadd($v->money, $v->money_yf, 2),
                  'lease_num' => $order_good->lease_num,
                  'unit_type_name' => $order_good->unit_type == 2 ? '天' : '月',
                  'good_num' => $order_good->num,
                  'user_name' => $v->user_name,
			            'money_yf' => $v->money_yf,
                  'phone' => $v->user->username,
                  'send_type' => $order_good->send_type,
                  'state' => $v->state,
                  'state_name' => $this->state_arr[$v->state],
                  'created_time' => date("Y-m-d H:i:s", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $order_data,
            'totalPage' => $order_query->count(),
            'currentPage' => $page,
            'perPage' => OrderInfo::PAGE_SIZE
        ]);
  	}

    //订单详情
    public function actionOrderInfo() {
      $id = Yii::$app->request->post('id', 0);
      $order = OrderInfo::findOne($id);
      if (empty($order)) {
        return Re::data(null, '订单信息读取失败', Re::ERROR);
      }
      $good_list = OrderInfoGood::find()->where(['order_id' => $id])->all();
      $good_data = [];
      if ($good_list) {
        foreach ($good_list as $v1) {
          $unit_type_name = $v1->unit_type == 2 ? '天' : '个月';
          $good_data[] = [
            'good_id' => $v1->good_id,
            'good_name' => $v1->good->name,
            'num' => $v1->num,
            'unit_price' => $v1->unit_price,
            'zl_time' => $v1->start_at ? date("Y-m-d", $v1->start_at).'-'.date("Y-m-d", $v1->end_at) : '',
            'specs_name' => $v1->specs_name,
            'unit_type' => $v1->unit_type,
            'unit_type_name' => $unit_type_name,
            'lease_num' => $v1->lease_num.$unit_type_name,
            'start_date' => date("Y-m-d", $v1->start_at),
            'end_date' => date("Y-m-d", $v1->end_at),
            'send_type' => $v1->send_type,
            'send_type_name' => $v1->send_type == 1 ? '自提' : '物流',
          ];
        }
      }
      $order_data = [
        'id' => $order->id,
        'user_name' => $order->user_name,
        'agreement_name' => $order->agreement_name,
        'money_yf' => $order->money_yf,
        'code' => $order->code,
        'file' => $order->file,
        'phone' => $order->user->username,
        'name' => $order->user->name,
        'order_sn' => $order->order_sn,
        'money' => bcadd($order->money, $order->money_yf, 2),
        'state' => $order->state,
        'state_name' => $this->state_arr[$order->state],
        'created_time' => date("Y-m-d H:i:s", $order->created_at),
        'address_name' => $order->address_name,
        'address_phone' => $order->address_phone,
        'address' => $order->address,
        'order_send_code' => $order->order_send_code,
        'order_send_name' => $order->order_send_name,
        'remark' => $order->remark,
        'good_list' => $good_data,
      ];
      return Re::data(['data' => $order_data]);
    }

    //编辑订单
    public function actionEditOrder(){
      $id = Yii::$app->request->post('id', 0);
      $post = Yii::$app->request->post();
      $post['updated_at'] = time();
      return $this->edit(OrderInfo::class, $id, $post);
    }

    //发货
    public function actionSendOrder() {
      $id = Yii::$app->request->post('id', 0);
      $send_name = Yii::$app->request->post('send_name', '');
      $send_code = Yii::$app->request->post('send_code', '');
      $order = OrderInfo::findOne($id);
      $order->state = 2;
      $order->order_send_name = $send_name;
      $order->order_send_code = $send_code;
      $order->send_at = time();
      $order->save();
      return Re::data();
    }

    //修改订单状态
    public function actionChangeOrderStatus() {
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 0);
      $order_info = OrderInfo::findOne($id);
      if (!$order_info) {
          return Re::data(null, '订单信息读取失败', Re::ERROR);
      }
      $order_info->status = $status;
      $order_info->save();
      return Re::data();
    }

    //交易完成
    public function actionOrderSuccess() {
      $id = Yii::$app->request->post('id', 0);
      $order = OrderInfo::findOne($id);
      $order->state = 3;
      $order->finsh_at = time();
      $order->save();
      return Re::data();
    }

    public function actionAuditOrder() {
      $id = Yii::$app->request->post('id', 0);
      $result = Yii::$app->request->post('result', 1);
      $reason = Yii::$app->request->post('reason', '');
      $order = OrderInfo::findOne($id);
      $order->state = $result == 1 ? 5 : 6;
      $order->reason = $reason;
      $order->save();
      if ($result == 1) {
        $good_list = OrderInfoGood::find()->where(['order_id' => $id])->all();
        if ($good_list) {
          foreach ($good_list as $v) {
            $good = $v->good;
            $good->store += $v->num;
            $good->save();
          }
        }
        $this->refund($order, $order->money);
      }
      return Re::data();
    }

    //线下订单列表
  	public function actionOfflineOrderList() {
  		$page = Yii::$app->request->post('page', 0);
      $page_size = Yii::$app->request->post('page_size', 20);
      $user_name = Yii::$app->request->post('user_name', '');
      $agreement_name = Yii::$app->request->post('agreement_name', '');
      $order_query = OrderOffline::find()->where(['status' => 1]);
      if ($user_name) {
        $order_query->andWhere(['like', 'user_name', $user_name]);
      }
      if ($agreement_name) {
        $order_query->andWhere(['like', 'agreement_name', $agreement_name]);
      }
  		$list = $order_query->orderBy("created_at desc")->limit($page_size)->offset($page_size*$page)->all();
      return Re::data([
          'data' => $list,
          'totalPage' => $order_query->count(),
          'currentPage' => $page,
          'perPage' => OrderOffline::PAGE_SIZE
      ]);
  	}

    public function actionEditOfflineOrder(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        return $this->edit(OrderOffline::class, $id, $post);
    }

    public function actionChangeOfflineOrderStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $order_offline = OrderOffline::findOne($id);
        if (empty($order_offline)) {
            return Re::data(null, '订单信息读取失败', Re::ERROR);
        }
        $order_offline->status = $status;
        if (!$order_offline->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }


    private function refund($order, $money) {
      $out_refund_no = OrderInfo::generateCode() . date('YmdHis') . $order->user_id;
  		$param["appid"] = Yii::$app->params['wx_pay']['app_id'];
  		$param["mch_id"] = Yii::$app->params['wx_pay']['mch_id'];
  		$param["nonce_str"] = md5(time().rand().$order->order_sn);
  		$param["out_trade_no"] = $order->order_sn;
  		$param["out_refund_no"] = $out_refund_no;
  		$param["total_fee"] = $order->money * 100; //金额单位:分
  		$param["refund_fee"] = $money * 100; //金额单位:分
  		$sign = $this->getSign($param);
  		$param["sign"] = $sign;
  		$xml = $this->ToXml($param);
  		$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
  		$response = $this->curl($url, $xml);
  		$res = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)));
  		return $res;
  	}

  	private function ToXml($param) {
  		if(!is_array($param) || count($param) <= 0)
  		{
  				throw new WxPayException("数组数据异常！");
  			}

  			$xml = "<xml>";
  			foreach ($param as $key=>$val)
  			{
  				if (is_numeric($val)){
  					$xml.="<".$key.">".$val."</".$key.">";
  				}else{
  					$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  				}
  				}
  				$xml.="</xml>";
  				return $xml;
  	}

  	private function getSign($param) {
  		//签名步骤一：按字典序排序参数
  		ksort($param);
  		$string = $this->ToUrlParams($param);
  		//签名步骤二：在string后加入KEY
  		$string = $string . "&key=".Yii::$app->params['wx_pay']['key'];;
  		//签名步骤三：MD5加密
  		$string = md5($string);
  		//签名步骤四：所有字符转为大写
  		$result = strtoupper($string);
  		return $result;
  	}

  	/**
  	 * 格式化参数格式化成url参数
  	 */
  	private function ToUrlParams($param) {
  		$buff = "";
  		foreach ($param as $k => $v)
  		{
  			if($k != "sign" && $v != "" && !is_array($v)){
  				$buff .= $k . "=" . $v . "&";
  			}
  		}

  		$buff = trim($buff, "&");
  		return $buff;
  	}

  	private function curl($url, $data)	{
  		//echo getcwd();die;
  		//echo Yii::$app->params['domain'].'/public/cert/apiclient_key.pem';die;
  		$ch = curl_init();
  		curl_setopt($ch, CURLOPT_URL, $url);
  		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  		curl_setopt($ch, CURLOPT_HEADER, FALSE);
  		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  		curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
  		curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/public/cert/apiclient_cert.pem');
  		curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  		curl_setopt($ch, CURLOPT_SSLKEY, getcwd().'/public/cert/apiclient_key.pem');
  		curl_setopt($ch, CURLOPT_POST, true);
  		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  		$data = curl_exec($ch);
      return $data;
  	}
}
